package cn.pconline.autoclub.web.admin;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.gelivable.auth.entity.GeliSession;
import org.gelivable.auth.entity.GeliUser;
import org.gelivable.webmvc.JSONBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubMedal;
import cn.pconline.autoclub.entity.ClubMedalRelation;
import cn.pconline.autoclub.service.ClubMedalService;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.MessageService;
import cn.pconline.autoclub.service.SendMsgService;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;

/**
 *
 * @author ppc
 */
@Controller
@RequestMapping(value = "/admin")
public class AdminClubMedalController {

    @Autowired
    private ClubMedalService clubMedalService;
    @Autowired
    private ClubService clubService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private SendMsgService sendMsgService;
    
    private static final int DEFAULT_PAGESIZE = 20;
    private static final int MAX_PAGESIZE = 100;
    private static final Logger log = LoggerFactory.getLogger(AdminClubMedalController.class);

    /**
     * 成功返回消息
     *
     * @param resp
     * @param navTabId
     * @param msg
     * @param callbackType closeCurrent 关闭当前tab forward reload
     */
    private void successMsg(HttpServletResponse resp, String navTabId, String msg, String callbackType) {
        try {
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            out.println(new JSONBuilder().put("statusCode", 200).put("message", msg).put("navTabId", navTabId).put("callbackType", callbackType).toString());
        } catch (IOException ex) {
            log.error("set successMsg fail!", ex);
        }
    }

    private void errorMsg(HttpServletResponse resp, String msg) {
        try {
            resp.setCharacterEncoding("UTF-8");
            PrintWriter out = resp.getWriter();
            out.println(new JSONBuilder().put("statusCode", 300).put("message", msg).toString());
        } catch (IOException ex) {
            log.error("set errorMsg fail!", ex);
        }
    }

    /**
     * 勋章列表
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/medal/listMedal.do")
    public String listClubMedal(HttpServletRequest req, HttpServletResponse resp) {
        int pageNo = WebUtils.paramInt(req, "pageNum", 1);
        int pageSize = WebUtils.paramInt(req, "pageSize", DEFAULT_PAGESIZE, 1, MAX_PAGESIZE);
        Pager<ClubMedal> pager = clubMedalService.listClubMedal(pageNo, pageSize);
        req.setAttribute("pager", pager);
        return "admin/medal/list";
    }

    /**
     * 创建勋章
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/medal/create.do", method = RequestMethod.POST)
    public void createClubMedal(HttpServletRequest req, HttpServletResponse resp) {
        String name = WebUtils.param(req, "name", "");
        String url = WebUtils.param(req, "url", "");
        if (StringUtils.isBlank(name)) {
            errorMsg(resp, "名称不能为空");
            return;
        }
        if (StringUtils.isBlank(url)) {
            errorMsg(resp, "勋章图片不能为空");
            return;
        }
        GeliUser geliUser = GeliSession.getCurrentUser();
        if (geliUser != null) {
            ClubMedal clubMedal = new ClubMedal();
            clubMedal.setName(name);
            clubMedal.setUrl(url);
            clubMedal.setCreateBy(geliUser.getUserId());
            long medalId = clubMedalService.createClubMedal(clubMedal);
            if (medalId > 0) {
                successMsg(resp, "list-medal", "创建成功", "closeCurrent");
            } else {
                errorMsg(resp, "创建失败");
            }
        } else {
            errorMsg(resp, "请登录后操作");
        }
    }

    /**
     * 修改勋章
     *
     * @param req
     * @param resp
     */
    @RequestMapping(value = "/medal/update.do", method = RequestMethod.POST)
    public void updateClubMedal(HttpServletRequest req, HttpServletResponse resp) {
        long medalId = WebUtils.paramLong(req, "medalId", 0);
        String name = WebUtils.param(req, "name", "");
        String url = WebUtils.param(req, "url", "");
        if (StringUtils.isBlank(name)) {
            errorMsg(resp, "名称不能为空");
            return;
        }
        if (StringUtils.isBlank(url)) {
            errorMsg(resp, "勋章图片不能为空");
            return;
        }
        ClubMedal clubMedal = clubMedalService.findClubMedalById(medalId);
        if (clubMedal != null) {
            clubMedal.setName(name);
            clubMedal.setUrl(url);
            clubMedal.setUpdateAt(new Date());
            int count = clubMedalService.updateClubMedal(clubMedal);
            if (count > 0) {
                successMsg(resp, "list-medal", "修改成功", "closeCurrent");
            } else {
                errorMsg(resp, "修改失败");
            }
        } else {
            errorMsg(resp, "找不到该勋章");
        }
    }
    /**
     * 删除勋章
     * @param req
     * @param resp 
     */
    @RequestMapping(value="/medal/deleteMedal.do",method= RequestMethod.POST)
    public void deleteMedal(HttpServletRequest req,HttpServletResponse resp){
        long medalId = WebUtils.paramLong(req, "medalId", 0);
        ClubMedal clubMedal = clubMedalService.findClubMedalById(medalId);
        if( clubMedal == null ){
            errorMsg(resp, "该勋章不存在");
            return;
        }
        int count = clubMedalService.deleteMedal(clubMedal);
        if(count>0){
            successMsg(resp, "list-medal", "删除成功", null);
        }else{
            errorMsg(resp, "删除失败");
        }
    }
    /**
     * 创建勋章页面跳转
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/medal/goToCreate", method = RequestMethod.GET)
    public String goToCreate(HttpServletRequest req, HttpServletResponse resp) {
        return "admin/medal/create";
    }
    /**
     * 修改勋章页面跳转
     *
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "/medal/editMedal.do", method = RequestMethod.GET)
    public String editMedal(HttpServletRequest req, HttpServletResponse resp) {
        long medalId = WebUtils.paramLong(req, "medalId", 0);
        ClubMedal clubMedal = clubMedalService.findClubMedalById(medalId);
        req.setAttribute("clubMedal", clubMedal);
        return "admin/medal/create";
    }
    /**
     * 车友会颁发勋章页面跳转
     * @param req
     * @param resp
     * @return 
     */
    @RequestMapping(value = "/medal/addMedal.do")
    public String addMedal(HttpServletRequest req, HttpServletResponse resp) {
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        List<ClubMedal> clubMedals = clubMedalService.listClubMedalByClubId(clubId);
        List<ClubMedal> medals = clubMedalService.listClubMedal();
        medals = clubMedalService.removeHasMedal(medals, clubMedals);
        req.setAttribute("clubMedals", clubMedals);
        req.setAttribute("medals", medals);
        return "admin/medal/issueMedal";
    }
    /**
     * 颁发勋章
     * @param req
     * @param resp 
     */
    @RequestMapping(value="/medal/issueMedal.do",method= RequestMethod.POST)
    public void issueMedal(HttpServletRequest req, HttpServletResponse resp) {
        long medalId = WebUtils.paramLong(req, "medalId", 0);
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        Club club = clubService.getValidClub(clubId);
        if (club != null) {
            ClubMedal clubMedal = clubMedalService.findClubMedalById(medalId);
            if (clubMedal == null) {
                errorMsg(resp, "medalId有误");
                return;
            }
            GeliUser geliUser = GeliSession.getCurrentUser();
            if (geliUser == null) {
                errorMsg(resp, "请登录后操作");
                return;
            }
            ClubMedalRelation clubMedalRelation = new ClubMedalRelation();
            clubMedalRelation.setClubId(club.getClubId());
            clubMedalRelation.setMedalId(clubMedal.getMedalId());
            long id = clubMedalService.issueClubMedal(clubMedalRelation);
            
            // 给车友会全部成员发送系统消息
            String msgContent = new StringBuilder()
    			.append("恭喜您，您所在的车友会--")
    			.append(messageService.assembleClubUrl(club.getClubUrl(), club.getName()))
    			.append("获得了")
    			.append(clubMedal.getName().replace("勋章", ""))
    			.append("勋章一枚！")
    			.toString();
            sendMsgService.createClubMedalSysMsg(geliUser.getUserId(), clubId, msgContent);
            
            successMsg(resp, "club-addMedal", "颁发成功", "reload");
        } else {
            errorMsg(resp, "clubId有误");
        }
    }
    /**
     * 取消指定车友会勋章
     * @param req
     * @param resp 
     */
    @RequestMapping(value="/medal/cancelMedal.do",method= RequestMethod.POST)
    public void cancelMedal(HttpServletRequest req,HttpServletResponse resp){
        long clubId = WebUtils.paramLong(req, "clubId", 0);
        long medalId = WebUtils.paramLong(req, "medalId", 0);
        Club club = clubService.getValidClub(clubId);
        if(club==null){
            errorMsg(resp, "车友会ID有误");
            return;
        }
        ClubMedalRelation clubMedalRelation = clubMedalService.getClubMedalRelation(clubId, medalId);
        if(clubMedalRelation == null){
            errorMsg(resp, "车友会没有该勋章");
            return;
        }
        int count = clubMedalService.cancelMedal(clubMedalRelation);
        if(count>0){
            successMsg(resp, "club-addMedal", "取消成功", null);
            return;
        }else{
            errorMsg(resp, "取消失败");
        }
        
    }
}
